package com.m3839.sdk.pay.ui;

import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.m3839.sdk.anti.core.AntiManager;
import com.m3839.sdk.common.base.BaseDialogFragment;
import com.m3839.sdk.common.core.Constant;
import com.m3839.sdk.common.core.ErrorConstant;
import com.m3839.sdk.common.core.SdkConfiguration;
import com.m3839.sdk.common.util.AppUtils;
import com.m3839.sdk.common.util.LogUtils;
import com.m3839.sdk.common.util.ResourcesUtils;
import com.m3839.sdk.common.util.StringUtils;
import com.m3839.sdk.common.util.ToastUtil;
import com.m3839.sdk.login.core.LoginManager;
import com.m3839.sdk.login.bean.InternalUser;
import com.m3839.sdk.pay.bean.PayInfo;
import com.m3839.sdk.pay.bean.PayLimit;
import com.m3839.sdk.pay.bean.PayResult;
import com.m3839.sdk.pay.constant.PayConstant;
import com.m3839.sdk.pay.task.PayTask;

/**
 * Description:支付限额提醒
 *
 * @author 陈宝阳
 * @create 2020/8/14 15:58
 */
public class PayLimitDialogFragment extends BaseDialogFragment {

  private static final int REQUEST_CODE_USER = 1003;

  private static final String KEY_PAY_LIMIT = "pay_limit";

  public static final String KEY_NICK = "nick";
  public static final String KEY_UID = "uid";
  public static final String KEY_LOGIN_TYPE = "platform";
  public static final String KEY_APP_ID = "app_id";

  private TextView warmTipTv;
  private TextView detailTv;
  private Button negativeBtn;
  private Button positiveBtn;

  private PayLimit payLimit;
  private PayInfo payInfo;

  private PayTask payTask;

  public static PayLimitDialogFragment newInstance(PayLimit payLimit, PayInfo payInfo) {
    PayLimitDialogFragment fragment = new PayLimitDialogFragment();
    Bundle data = new Bundle();
    data.putParcelable(KEY_PAY_LIMIT, payLimit);
    data.putParcelable(PayConstant.HYKB_KEY_PAY_INFO, payInfo);
    fragment.setArguments(data);
    return fragment;
  }

  public void setPayTask(PayTask payTask) {
    this.payTask = payTask;
  }

  @Override
  protected void parseArgs() {
    payLimit = getArguments().getParcelable(KEY_PAY_LIMIT);
    payInfo = getArguments().getParcelable(PayConstant.HYKB_KEY_PAY_INFO);
  }

  @Override
  protected String getLayoutName() {
    return "hykb_anti_dialog_fragment";
  }

  @Override
  protected void initView(View view) {
    warmTipTv = view.findViewById(getId("tv_warm_tip"));
    detailTv = view.findViewById(getId("tv_detail"));
    negativeBtn = view.findViewById(getId("dlg_btn_negative"));
    positiveBtn = view.findViewById(getId("dlg_btn_positive"));
    viewHolder.setViewVisible("tv_public_policy_tip", false);
  }

  @Override
  protected void setContent() {
    if (payLimit != null) {
      if (payLimit.linkBean != null && !TextUtils.isEmpty(payLimit.linkBean.name)
          && !TextUtils.isEmpty(payLimit.linkBean.url)) {
        detailTv.setText(payLimit.linkBean.name);
        detailTv.setVisibility(View.VISIBLE);
      } else {
        detailTv.setVisibility(View.GONE);
      }

      // 设置支付限额内容
      setPayLimitContent();

      //设置温馨提示
      if (!TextUtils.isEmpty(payLimit.tips)) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
          warmTipTv.setText(
              Html.fromHtml(payLimit.tips, Html.FROM_HTML_MODE_LEGACY));
        } else {
          warmTipTv.setText(Html.fromHtml(payLimit.tips));
        }
        warmTipTv.setVisibility(View.VISIBLE);
      } else {
        warmTipTv.setVisibility(View.GONE);
      }

      if (payLimit.buttonBeanList != null && payLimit.buttonBeanList.size() > 0) {
        negativeBtn.setText(payLimit.buttonBeanList.get(0).name);
      }

      if (payLimit.buttonBeanList != null && payLimit.buttonBeanList.size() > 1) {
        positiveBtn.setText(payLimit.buttonBeanList.get(1).name);
        positiveBtn.setVisibility(View.VISIBLE);
        viewHolder.setViewVisible("view_btn_line", true);
        negativeBtn.setBackgroundResource(
            ResourcesUtils.getDrawableId(getActivity(), "hykb_bg_default_dialog_left_btn"));
      } else {
        positiveBtn.setVisibility(View.GONE);
        viewHolder.setViewVisible("view_btn_line", false);
        negativeBtn.setBackgroundResource(
            ResourcesUtils.getDrawableId(getActivity(), "hykb_bg_default_dialog_single_btn"));
      }
    }
  }

  private void setPayLimitContent() {
    //设置文案内容
    if (!TextUtils.isEmpty(payLimit.content)) {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        viewHolder.setTextView("tv_public_policy",Html.fromHtml(payLimit.content, Html.FROM_HTML_MODE_LEGACY));
      } else {
        viewHolder.setTextView("tv_public_policy", Html.fromHtml(payLimit.content));
      }
    }
  }

  @Override
  protected void initListener() {
    detailTv.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if (payLimit != null && payLimit.linkBean != null && StringUtils.isValidHttpUrl(
            payLimit.linkBean.url)) {
          //用手机浏览器打开点击的链接
          Intent intent = new Intent();
          intent.setAction("android.intent.action.VIEW");
          Uri uri = Uri.parse(payLimit.linkBean.url);
          intent.setData(uri);
          startActivity(intent);
        }
      }
    });

    negativeBtn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if (payLimit.buttonBeanList != null && payLimit.buttonBeanList.size() > 0) {
          handleAction(payLimit.buttonBeanList.get(0).func);
        }
      }
    });

    positiveBtn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if (payLimit.buttonBeanList != null && payLimit.buttonBeanList.size() > 1) {
          handleAction(payLimit.buttonBeanList.get(1).func);
        }
      }
    });
  }

  private void handleAction(String action) {
    if(Constant.ACTION_WSSFXX.equals(action)) {
      openIdCardActivity();
      return;
    }

    if(Constant.ACTION_EXIT_POPUP.equals(action)){
      // 关闭弹窗后
      PayResult result = new PayResult();
      result.payInfo = payInfo;
      result.resultCode = ErrorConstant.HYKB_CODE_PAY_LIMIT_DIALOG_CLOSE;
      result.message = ErrorConstant.ERR_MSG_PAY_LIMIT_DIALOG_CLOSE;
      payTask.handlePayCallBack(result);
      dismissAllowingStateLoss();
    }

  }

  /**
   * 跳转到快爆完成实名认证
   */
  private void openIdCardActivity() {
    if (!AppUtils.checkVersionCode(getActivity(), Constant.HYKB_PACKAGE_NAME,
            Constant.HYKB_SUPPORT_LOW_VERSION)) {
      payTask.resetPayFlag();
      AntiManager.getInstance().toRealNameWeb(getActivity());
    } else {
      InternalUser user = LoginManager.getInstance().getInternalUser();
      if (user == null) {
        return;
      }

      Intent intent = new Intent("android.intent.action.VIEW");
      intent.putExtra(KEY_UID, user.getUserId());
      intent.putExtra(KEY_NICK, user.getNick());
      intent.putExtra(KEY_LOGIN_TYPE, user.getType());
      intent.putExtra(KEY_APP_ID, SdkConfiguration.getGameId());
      //固定字段
      intent.putExtra("key", "loginsdk");
      ComponentName componentName = new ComponentName(Constant.HYKB_PACKAGE_NAME,
              "com.xmcy.hykb.app.ui.idcard.IdCardActivity");
      intent.setComponent(componentName);
      startActivityForResult(intent, REQUEST_CODE_USER);
    }
  }

  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE_USER && data != null) {
      boolean status = data.getBooleanExtra("status", false);
      String msg = data.getStringExtra("msg");
      LogUtils.i("m3839", "status = " + status + ", msg = " + msg);
      if (!status) {
        if (!TextUtils.isEmpty(msg)) {
          ToastUtil.showToast(getActivity(), msg);
        }
        return;
      }
      PayResult result = new PayResult();
      result.payInfo = payInfo;
      result.resultCode = ErrorConstant.HYKB_CODE_PAY_LIMIT_DIALOG_CLOSE;
      result.message = ErrorConstant.ERR_MSG_PAY_LIMIT_DIALOG_CLOSE;
      payTask.handlePayCallBack(result);
      dismissAllowingStateLoss();
    }
  }
}
